import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:oktoast/oktoast.dart';
import 'package:yurun_smartmerchants/generated/json/base/json_convert_content.dart';
import 'package:yurun_smartmerchants/global.dart';
import 'package:yurun_smartmerchants/models/staff_list_entity.dart';
import 'package:yurun_smartmerchants/net/ApiInterface.dart';
import 'package:yurun_smartmerchants/res/colours.dart';
import 'package:yurun_smartmerchants/routes/routes.dart';
import 'package:yurun_smartmerchants/utils/app_size.dart';
import 'package:yurun_smartmerchants/utils/evenbus_utils.dart';
import 'package:yurun_smartmerchants/utils/loading_utils.dart';
import 'package:yurun_smartmerchants/view/EmptyView.dart';
import 'package:yurun_smartmerchants/view/custom_loadmore_footer.dart';
import 'package:yurun_smartmerchants/view/custom_refresh_header.dart';

class StaffManagementPage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return _StaffManagementPageState();
  }
}

class _StaffManagementPageState extends State<StaffManagementPage> {
  bool empty = false;
  bool owned = false;
  int page = 0;
  final int size = 15;
  List<StaffListContent> staffList = List();
  EasyRefreshController _easyRefreshController = EasyRefreshController();
  bool isFirstLoad = true;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    owned = Global.prefs.getBool(Global.owned);
    print('owned:$owned');
    WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
      _getStaffList();
    });

    EventBus().on('refresh_staff', (arg) {
      isFirstLoad = true;
      _getStaffList();
    });
  }

  void statusRefreshLoad(load,last){
    if(page == 0){
      _easyRefreshController.finishRefresh(success: load);
    }
    _easyRefreshController.finishLoad(success: load,noMore: last);
  }


  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Colours.white,
        centerTitle: true,
        iconTheme: IconThemeData(color: Colours.app_words),
        title: Text(
          '员工管理',
          style: TextStyle(fontSize: 18, color: Colours.app_words),
        ),
      ),
      body: Container(
        color: Colours.app_background,
        child: Column(
          children: <Widget>[
            Expanded(
              child: CupertinoScrollbar(
                child: EasyRefresh(
                    controller: _easyRefreshController,
                    header: CustomRefreshHeader(),
                    footer: CustomLoadFooter(),
                    emptyWidget: empty ? EmptyView(content: '暂无数据',) : null,
                    onRefresh: () async {
                      isFirstLoad = false;
                      page = 0;
                      _getStaffList();
                    },
                    onLoad: () async {
                      isFirstLoad = false;
                      page ++;
                      _getStaffList();
                    },
                    child: ListView.separated(
                      padding: EdgeInsets.only(top: AppSize.height(20),bottom: AppSize.height(20)),
                      itemBuilder: (BuildContext context, int index) {
                        return _generateItemView(index);
                      },
                      separatorBuilder: (BuildContext context, int index) {
                        return Divider(
                          thickness: AppSize.height(1),
                          color: Colours.app_background,
                          height: AppSize.height(1),
                        );
                      },
                      itemCount: staffList.length,
                    )
                ),),
            ),
            Offstage(
              offstage: !owned,
              child: Container(
                height: AppSize.height(135),
                color: Colors.white,
                alignment: Alignment.center,
                child: Container(
                  height: AppSize.height(90),
                  margin: EdgeInsets.only(
                      left: AppSize.width(20), right: AppSize.width(20)),
                  child: RaisedButton(
                    onPressed: () {
                      Navigator.pushNamed(context, add_staff_page);
                    },
                    color: Colours.app_main,
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: <Widget>[
                        Padding(
                          padding: EdgeInsets.only(
                            top: AppSize.height(4),
                          ),
                          child: Icon(
                            Icons.add_circle_outline,
                            size: AppSize.sp(45),
                            color: Colours.white,
                          ),
                        ),
                        Padding(
                          padding: EdgeInsets.only(left: AppSize.width(10)),
                          child: Text(
                            '新增员工',
                            style: TextStyle(
                                fontSize: AppSize.sp(32), color: Colours.white),
                          ),
                        )
                      ],
                    ),
                  ),
                ),
              ),
            )
          ],
        ),
      ),
    );
  }

  Widget _generateItemView(index) {
    return Material(
      color: Colors.white,
      child: InkWell(
        onTap: (){
          Navigator.pushNamed(context, staff_detail_page,arguments: staffList[index]);
        },
        child: Container(
          height: AppSize.height(128),
          child: Row(
            children: <Widget>[
              Expanded(
                  flex: 3,
                  child: Container(
                    alignment: Alignment.center,
                    child: Container(
                      width: 100.w,
                      height: 100.w,
                      child: (staffList[index].account.url == null || staffList[index].account.url.isEmpty) ?
                      CircleAvatar(child: Icon(Icons.person,color: Colours.white,size: 70.sp,),backgroundColor: Color(0xffadb0ba),) :
                      ClipOval(child: Image.network(staffList[index].account.url,fit: BoxFit.cover,))
                      ),
                    ),
              ),
              Expanded(
                  flex: 10,
                  child: Container(
                    alignment: Alignment.center,
                    child: Column(
                      mainAxisSize: MainAxisSize.min,
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: <Widget>[
                        Container(
                          child: Row(
                            children: <Widget>[
                              Container(
                                child: Text(
                                  staffList[index].name,
                                  style: TextStyle(
                                      fontSize: AppSize.sp(32),
                                      color: Color(0xff434343)),
                                ),
                              ),
                              Offstage(
                                offstage: !staffList[index].owned,
                                child: Container(
                                  alignment: Alignment.center,
                                  margin: EdgeInsets.only(left: AppSize.width(10),top: AppSize.height(4)),
                                  decoration: ShapeDecoration(
                                      color: Colours.app_main,
                                      shape: RoundedRectangleBorder(
                                          borderRadius:
                                          BorderRadius.all(Radius.circular(4)))),
                                  child: Padding(
                                    padding: EdgeInsets.only(
                                        left: AppSize.width(5),
                                        right: AppSize.width(5),
                                        bottom: AppSize.height(2)),
                                    child: Text(
                                      '管理员',
                                      style: TextStyle(
                                          fontSize: AppSize.sp(22),
                                          color: Colours.white),
                                    ),
                                  ),
                                ),
                              ),
                            ],
                          ),
                        ),
                        Container(
                          margin: EdgeInsets.only(top: AppSize.height(10)),
                          child: Text(
                            staffList[index].phone,
                            style: TextStyle(
                                fontSize: AppSize.sp(26), color: Color(0xff898989)),
                          ),
                        ),
                      ],
                    ),
                  )),
              Expanded(
                  flex: 2,
                  child: Container(
                    child: Icon(
                      Icons.arrow_forward_ios,
                      color: Color(0xffc7c7c7),
                      size: AppSize.sp(32),
                    ),
                  )),
            ],
          ),
        ),
      ),
    );
  }

  void _getStaffList(){
    if(isFirstLoad) {
      LoadingUtil.showLoading(context, tip: '加载中...');
    }
    ApiInterface.getStaffList(page, size).then((value){
      StaffListEntity staffListEntity = JsonConvert.fromJsonAsT<StaffListEntity>(value);
      setState(() {
        if(page == 0){
          staffList.clear();
        }
        if(staffListEntity.content != null && staffListEntity.content.length > 0){
          staffList.addAll(staffListEntity.content);
        }
        if(staffList.length == 0){
          empty = true;
        }else{
          empty = false;
        }
      });
      statusRefreshLoad(true, staffListEntity.last);
      if (staffList.length > 0) {
        if (!isFirstLoad && page == 0) {
          showToast("刷新成功");
        } else if (staffListEntity.last && page > 0) {
          showToast("暂无更多数据");
        }
      }
    }).catchError((error){
      statusRefreshLoad(false, true);
    }).whenComplete((){
      LoadingUtil.hideLoading(context);
    });
  }

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    _easyRefreshController.dispose();
    EventBus().off('refresh_staff');
  }
}
